documentation
[lhc/web/wiklou.git] / includes / Export.php
1 <?php
2 # Copyright (C) 2003, 2005, 2006 Brion Vibber <brion@pobox.com>
3 # http://www.mediawiki.org/
4 #
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 2 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License along
16 # with this program; if not, write to the Free Software Foundation, Inc.,
17 # 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
18 # http://www.gnu.org/copyleft/gpl.html
19 /**
20 *
21 * @package MediaWiki
22 * @subpackage SpecialPage
23 */
24
25 /** */
26 require_once( 'Revision.php' );
27
28 define( 'MW_EXPORT_FULL', 0 );
29 define( 'MW_EXPORT_CURRENT', 1 );
30
31 define( 'MW_EXPORT_BUFFER', 0 );
32 define( 'MW_EXPORT_STREAM', 1 );
33
34 define( 'MW_EXPORT_TEXT', 0 );
35 define( 'MW_EXPORT_STUB', 1 );
36
37
38 /**
39 * @package MediaWiki
40 * @subpackage SpecialPage
41 */
42 class WikiExporter {
43
44 var $list_authors = false ; # Return distinct author list (when not returning full history)
45 var $author_list = "" ;
46
47 /**
48 * If using MW_EXPORT_STREAM to stream a large amount of data,
49 * provide a database connection which is not managed by
50 * LoadBalancer to read from: some history blob types will
51 * make additional queries to pull source data while the
52 * main query is still running.
53 *
54 * @param Database $db
55 * @param int $history one of MW_EXPORT_FULL or MW_EXPORT_CURRENT
56 * @param int $buffer one of MW_EXPORT_BUFFER or MW_EXPORT_STREAM
57 */
58 function WikiExporter( &$db, $history = MW_EXPORT_CURRENT,
59 $buffer = MW_EXPORT_BUFFER, $text = MW_EXPORT_TEXT ) {
60 $this->db =& $db;
61 $this->history = $history;
62 $this->buffer = $buffer;
63 $this->writer = new XmlDumpWriter();
64 $this->sink = new DumpOutput();
65 $this->text = $text;
66 }
67
68 /**
69 * Set the DumpOutput or DumpFilter object which will receive
70 * various row objects and XML output for filtering. Filters
71 * can be chained or used as callbacks.
72 *
73 * @param mixed $callback
74 */
75 function setOutputSink( &$sink ) {
76 $this->sink =& $sink;
77 }
78
79 function openStream() {
80 $output = $this->writer->openStream();
81 $this->sink->writeOpenStream( $output );
82 }
83
84 function closeStream() {
85 $output = $this->writer->closeStream();
86 $this->sink->writeCloseStream( $output );
87 }
88
89 /**
90 * Dumps a series of page and revision records for all pages
91 * in the database, either including complete history or only
92 * the most recent version.
93 */
94 function allPages() {
95 return $this->dumpFrom( '' );
96 }
97
98 /**
99 * Dumps a series of page and revision records for those pages
100 * in the database falling within the page_id range given.
101 * @param int $start Inclusive lower limit (this id is included)
102 * @param int $end Exclusive upper limit (this id is not included)
103 * If 0, no upper limit.
104 */
105 function pagesByRange( $start, $end ) {
106 $condition = 'page_id >= ' . intval( $start );
107 if( $end ) {
108 $condition .= ' AND page_id < ' . intval( $end );
109 }
110 return $this->dumpFrom( $condition );
111 }
112
113 /**
114 * @param Title $title
115 */
116 function pageByTitle( $title ) {
117 return $this->dumpFrom(
118 'page_namespace=' . $title->getNamespace() .
119 ' AND page_title=' . $this->db->addQuotes( $title->getDbKey() ) );
120 }
121
122 function pageByName( $name ) {
123 $title = Title::newFromText( $name );
124 if( is_null( $title ) ) {
125 return new WikiError( "Can't export invalid title" );
126 } else {
127 return $this->pageByTitle( $title );
128 }
129 }
130
131 function pagesByName( $names ) {
132 foreach( $names as $name ) {
133 $this->pageByName( $name );
134 }
135 }
136
137
138 // -------------------- private implementation below --------------------
139
140 # Generates the distinct list of authors of an article
141 # Not called by default (depends on $this->list_authors)
142 # Can be set by Special:Export when not exporting whole history
143 function do_list_authors ( $page , $revision , $cond ) {
144 $fname = "do_list_authors" ;
145 wfProfileIn( $fname );
146 $this->author_list = "<contributors>";
147 $sql = "SELECT DISTINCT rev_user_text,rev_user FROM {$page},{$revision} WHERE page_id=rev_page AND " . $cond ;
148 $result = $this->db->query( $sql, $fname );
149 $resultset = $this->db->resultObject( $result );
150 while( $row = $resultset->fetchObject() ) {
151 $this->author_list .= "<contributor>" .
152 "<username>" .
153 htmlentities( $row->rev_user_text ) .
154 "</username>" .
155 "<id>" .
156 $row->rev_user .
157 "</id>" .
158 "</contributor>";
159 }
160 wfProfileOut( $fname );
161 $this->author_list .= "</contributors>";
162 }
163
164 function dumpFrom( $cond = '' ) {
165 $fname = 'WikiExporter::dumpFrom';
166 wfProfileIn( $fname );
167
168 $page = $this->db->tableName( 'page' );
169 $revision = $this->db->tableName( 'revision' );
170 $text = $this->db->tableName( 'text' );
171
172 if( $this->history == MW_EXPORT_FULL ) {
173 $join = 'page_id=rev_page';
174 } elseif( $this->history == MW_EXPORT_CURRENT ) {
175 if ( $this->list_authors && $cond != '' ) { // List authors, if so desired
176 $this->do_list_authors ( $page , $revision , $cond );
177 }
178 $join = 'page_id=rev_page AND page_latest=rev_id';
179 } else {
180 wfProfileOut( $fname );
181 return new WikiError( "$fname given invalid history dump type." );
182 }
183 $where = ( $cond == '' ) ? '' : "$cond AND";
184
185 if( $this->buffer == MW_EXPORT_STREAM ) {
186 $prev = $this->db->bufferResults( false );
187 }
188 if( $cond == '' ) {
189 // Optimization hack for full-database dump
190 $pageindex = 'FORCE INDEX (PRIMARY)';
191 $revindex = 'FORCE INDEX (PRIMARY)';
192 $straight = ' /*! STRAIGHT_JOIN */ ';
193 } else {
194 $pageindex = '';
195 $revindex = '';
196 $straight = '';
197 }
198 if( $this->text == MW_EXPORT_STUB ) {
199 $sql = "SELECT $straight * FROM
200 $page $pageindex,
201 $revision $revindex
202 WHERE $where $join
203 ORDER BY page_id";
204 } else {
205 $sql = "SELECT $straight * FROM
206 $page $pageindex,
207 $revision $revindex,
208 $text
209 WHERE $where $join AND rev_text_id=old_id
210 ORDER BY page_id";
211 }
212 $result = $this->db->query( $sql, $fname );
213 $wrapper = $this->db->resultObject( $result );
214 $this->outputStream( $wrapper );
215
216 if ( $this->list_authors ) {
217 $this->outputStream( $wrapper );
218 }
219
220 if( $this->buffer == MW_EXPORT_STREAM ) {
221 $this->db->bufferResults( $prev );
222 }
223
224 wfProfileOut( $fname );
225 }
226
227 /**
228 * Runs through a query result set dumping page and revision records.
229 * The result set should be sorted/grouped by page to avoid duplicate
230 * page records in the output.
231 *
232 * The result set will be freed once complete. Should be safe for
233 * streaming (non-buffered) queries, as long as it was made on a
234 * separate database connection not managed by LoadBalancer; some
235 * blob storage types will make queries to pull source data.
236 *
237 * @param ResultWrapper $resultset
238 * @access private
239 */
240 function outputStream( $resultset ) {
241 $last = null;
242 while( $row = $resultset->fetchObject() ) {
243 if( is_null( $last ) ||
244 $last->page_namespace != $row->page_namespace ||
245 $last->page_title != $row->page_title ) {
246 if( isset( $last ) ) {
247 $output = $this->writer->closePage();
248 $this->sink->writeClosePage( $output );
249 }
250 $output = $this->writer->openPage( $row );
251 $this->sink->writeOpenPage( $row, $output );
252 $last = $row;
253 }
254 $output = $this->writer->writeRevision( $row );
255 $this->sink->writeRevision( $row, $output );
256 }
257 if( isset( $last ) ) {
258 $output = $this->author_list . $this->writer->closePage();
259 $this->sink->writeClosePage( $output );
260 }
261 $resultset->free();
262 }
263 }
264
265 class XmlDumpWriter {
266
267 /**
268 * Returns the export schema version.
269 * @return string
270 */
271 function schemaVersion() {
272 return "0.3"; // FIXME: upgrade to 0.4 when updated XSD is ready, for the revision deletion bits
273 }
274
275 /**
276 * Opens the XML output stream's root <mediawiki> element.
277 * This does not include an xml directive, so is safe to include
278 * as a subelement in a larger XML stream. Namespace and XML Schema
279 * references are included.
280 *
281 * Output will be encoded in UTF-8.
282 *
283 * @return string
284 */
285 function openStream() {
286 global $wgContLanguageCode;
287 $ver = $this->schemaVersion();
288 return wfElement( 'mediawiki', array(
289 'xmlns' => "http://www.mediawiki.org/xml/export-$ver/",
290 'xmlns:xsi' => "http://www.w3.org/2001/XMLSchema-instance",
291 'xsi:schemaLocation' => "http://www.mediawiki.org/xml/export-$ver/ " .
292 "http://www.mediawiki.org/xml/export-$ver.xsd",
293 'version' => $ver,
294 'xml:lang' => $wgContLanguageCode ),
295 null ) .
296 "\n" .
297 $this->siteInfo();
298 }
299
300 function siteInfo() {
301 $info = array(
302 $this->sitename(),
303 $this->homelink(),
304 $this->generator(),
305 $this->caseSetting(),
306 $this->namespaces() );
307 return " <siteinfo>\n " .
308 implode( "\n ", $info ) .
309 "\n </siteinfo>\n";
310 }
311
312 function sitename() {
313 global $wgSitename;
314 return wfElement( 'sitename', array(), $wgSitename );
315 }
316
317 function generator() {
318 global $wgVersion;
319 return wfElement( 'generator', array(), "MediaWiki $wgVersion" );
320 }
321
322 function homelink() {
323 $page = Title::newFromText( wfMsgForContent( 'mainpage' ) );
324 return wfElement( 'base', array(), $page->getFullUrl() );
325 }
326
327 function caseSetting() {
328 global $wgCapitalLinks;
329 // "case-insensitive" option is reserved for future
330 $sensitivity = $wgCapitalLinks ? 'first-letter' : 'case-sensitive';
331 return wfElement( 'case', array(), $sensitivity );
332 }
333
334 function namespaces() {
335 global $wgContLang;
336 $spaces = " <namespaces>\n";
337 foreach( $wgContLang->getFormattedNamespaces() as $ns => $title ) {
338 $spaces .= ' ' . wfElement( 'namespace', array( 'key' => $ns ), $title ) . "\n";
339 }
340 $spaces .= " </namespaces>";
341 return $spaces;
342 }
343
344 /**
345 * Closes the output stream with the closing root element.
346 * Call when finished dumping things.
347 */
348 function closeStream() {
349 return "</mediawiki>\n";
350 }
351
352
353 /**
354 * Opens a <page> section on the output stream, with data
355 * from the given database row.
356 *
357 * @param object $row
358 * @return string
359 * @access private
360 */
361 function openPage( $row ) {
362 $out = " <page>\n";
363 $title = Title::makeTitle( $row->page_namespace, $row->page_title );
364 $out .= ' ' . wfElementClean( 'title', array(), $title->getPrefixedText() ) . "\n";
365 $out .= ' ' . wfElement( 'id', array(), strval( $row->page_id ) ) . "\n";
366 if( '' != $row->page_restrictions ) {
367 $out .= ' ' . wfElement( 'restrictions', array(),
368 strval( $row->page_restrictions ) ) . "\n";
369 }
370 return $out;
371 }
372
373 /**
374 * Closes a <page> section on the output stream.
375 *
376 * @access private
377 */
378 function closePage() {
379 return " </page>\n";
380 }
381
382 /**
383 * Dumps a <revision> section on the output stream, with
384 * data filled in from the given database row.
385 *
386 * @param object $row
387 * @return string
388 * @access private
389 */
390 function writeRevision( $row ) {
391 $fname = 'WikiExporter::dumpRev';
392 wfProfileIn( $fname );
393
394 $out = " <revision>\n";
395 $out .= " " . wfElement( 'id', null, strval( $row->rev_id ) ) . "\n";
396
397 $ts = wfTimestamp( TS_ISO_8601, $row->rev_timestamp );
398 $out .= " " . wfElement( 'timestamp', null, $ts ) . "\n";
399
400 if( $row->rev_deleted & MW_REV_DELETED_USER ) {
401 $out .= " " . wfElement( 'contributor', array( 'deleted' => 'deleted' ) ) . "\n";
402 } else {
403 $out .= " <contributor>\n";
404 if( $row->rev_user ) {
405 $out .= " " . wfElementClean( 'username', null, strval( $row->rev_user_text ) ) . "\n";
406 $out .= " " . wfElement( 'id', null, strval( $row->rev_user ) ) . "\n";
407 } else {
408 $out .= " " . wfElementClean( 'ip', null, strval( $row->rev_user_text ) ) . "\n";
409 }
410 $out .= " </contributor>\n";
411 }
412
413 if( $row->rev_minor_edit ) {
414 $out .= " <minor/>\n";
415 }
416 if( $row->rev_deleted & MW_REV_DELETED_COMMENT ) {
417 $out .= " " . wfElement( 'comment', array( 'deleted' => 'deleted' ) ) . "\n";
418 } elseif( $row->rev_comment != '' ) {
419 $out .= " " . wfElementClean( 'comment', null, strval( $row->rev_comment ) ) . "\n";
420 }
421
422 if( $row->rev_deleted & MW_REV_DELETED_TEXT ) {
423 $out .= " " . wfElement( 'text', array( 'deleted' => 'deleted' ) ) . "\n";
424 } elseif( isset( $row->old_text ) ) {
425 // Raw text from the database may have invalid chars
426 $text = strval( Revision::getRevisionText( $row ) );
427 $out .= " " . wfElementClean( 'text',
428 array( 'xml:space' => 'preserve' ),
429 strval( $text ) ) . "\n";
430 } else {
431 // Stub output
432 $out .= " " . wfElement( 'text',
433 array( 'id' => $row->rev_text_id ),
434 "" ) . "\n";
435 }
436
437 $out .= " </revision>\n";
438
439 wfProfileOut( $fname );
440 return $out;
441 }
442
443 }
444
445
446 /**
447 * Base class for output stream; prints to stdout or buffer or whereever.
448 */
449 class DumpOutput {
450 function writeOpenStream( $string ) {
451 $this->write( $string );
452 }
453
454 function writeCloseStream( $string ) {
455 $this->write( $string );
456 }
457
458 function writeOpenPage( $page, $string ) {
459 $this->write( $string );
460 }
461
462 function writeClosePage( $string ) {
463 $this->write( $string );
464 }
465
466 function writeRevision( $rev, $string ) {
467 $this->write( $string );
468 }
469
470 /**
471 * Override to write to a different stream type.
472 * @return bool
473 */
474 function write( $string ) {
475 print $string;
476 }
477 }
478
479 /**
480 * Stream outputter to send data to a file.
481 */
482 class DumpFileOutput extends DumpOutput {
483 var $handle;
484
485 function DumpFileOutput( $file ) {
486 $this->handle = fopen( $file, "wt" );
487 }
488
489 function write( $string ) {
490 fputs( $this->handle, $string );
491 }
492 }
493
494 /**
495 * Stream outputter to send data to a file via some filter program.
496 * Even if compression is available in a library, using a separate
497 * program can allow us to make use of a multi-processor system.
498 */
499 class DumpPipeOutput extends DumpFileOutput {
500 function DumpPipeOutput( $command, $file = null ) {
501 if( !is_null( $file ) ) {
502 $command .= " > " . wfEscapeShellArg( $file );
503 }
504 $this->handle = popen( $command, "w" );
505 }
506 }
507
508 /**
509 * Sends dump output via the gzip compressor.
510 */
511 class DumpGZipOutput extends DumpPipeOutput {
512 function DumpGZipOutput( $file ) {
513 parent::DumpPipeOutput( "gzip", $file );
514 }
515 }
516
517 /**
518 * Sends dump output via the bgzip2 compressor.
519 */
520 class DumpBZip2Output extends DumpPipeOutput {
521 function DumpBZip2Output( $file ) {
522 parent::DumpPipeOutput( "bzip2", $file );
523 }
524 }
525
526 /**
527 * Sends dump output via the p7zip compressor.
528 */
529 class Dump7ZipOutput extends DumpPipeOutput {
530 function Dump7ZipOutput( $file ) {
531 $command = "7za a -bd -si " . wfEscapeShellArg( $file );
532 parent::DumpPipeOutput( $command );
533 }
534 }
535
536
537
538 /**
539 * Dump output filter class.
540 * This just does output filtering and streaming; XML formatting is done
541 * higher up, so be careful in what you do.
542 */
543 class DumpFilter {
544 function DumpFilter( &$sink ) {
545 $this->sink =& $sink;
546 }
547
548 function writeOpenStream( $string ) {
549 $this->sink->writeOpenStream( $string );
550 }
551
552 function writeCloseStream( $string ) {
553 $this->sink->writeCloseStream( $string );
554 }
555
556 function writeOpenPage( $page, $string ) {
557 $this->sendingThisPage = $this->pass( $page, $string );
558 if( $this->sendingThisPage ) {
559 $this->sink->writeOpenPage( $page, $string );
560 }
561 }
562
563 function writeClosePage( $string ) {
564 if( $this->sendingThisPage ) {
565 $this->sink->writeClosePage( $string );
566 $this->sendingThisPage = false;
567 }
568 }
569
570 function writeRevision( $rev, $string ) {
571 if( $this->sendingThisPage ) {
572 $this->sink->writeRevision( $rev, $string );
573 }
574 }
575
576 /**
577 * Override for page-based filter types.
578 * @return bool
579 */
580 function pass( $page, $string ) {
581 return true;
582 }
583 }
584
585 /**
586 * Simple dump output filter to exclude all talk pages.
587 */
588 class DumpNotalkFilter extends DumpFilter {
589 function pass( $page ) {
590 return !Namespace::isTalk( $page->page_namespace );
591 }
592 }
593
594 /**
595 * Dump output filter to include or exclude pages in a given set of namespaces.
596 */
597 class DumpNamespaceFilter extends DumpFilter {
598 var $invert = false;
599 var $namespaces = array();
600
601 function DumpNamespaceFilter( &$sink, $param ) {
602 parent::DumpFilter( $sink );
603
604 $constants = array(
605 "NS_MAIN" => NS_MAIN,
606 "NS_TALK" => NS_TALK,
607 "NS_USER" => NS_USER,
608 "NS_USER_TALK" => NS_USER_TALK,
609 "NS_PROJECT" => NS_PROJECT,
610 "NS_PROJECT_TALK" => NS_PROJECT_TALK,
611 "NS_IMAGE" => NS_IMAGE,
612 "NS_IMAGE_TALK" => NS_IMAGE_TALK,
613 "NS_MEDIAWIKI" => NS_MEDIAWIKI,
614 "NS_MEDIAWIKI_TALK" => NS_MEDIAWIKI_TALK,
615 "NS_TEMPLATE" => NS_TEMPLATE,
616 "NS_TEMPLATE_TALK" => NS_TEMPLATE_TALK,
617 "NS_HELP" => NS_HELP,
618 "NS_HELP_TALK" => NS_HELP_TALK,
619 "NS_CATEGORY" => NS_CATEGORY,
620 "NS_CATEGORY_TALK" => NS_CATEGORY_TALK );
621
622 if( $param{0} == '!' ) {
623 $this->invert = true;
624 $param = substr( $param, 1 );
625 }
626
627 foreach( explode( ',', $param ) as $key ) {
628 $key = trim( $key );
629 if( isset( $constants[$key] ) ) {
630 $ns = $constants[$key];
631 $this->namespaces[$ns] = true;
632 } elseif( is_numeric( $key ) ) {
633 $ns = intval( $key );
634 $this->namespaces[$ns] = true;
635 } else {
636 wfDie( "Unrecognized namespace key '$key'\n" );
637 }
638 }
639 }
640
641 function pass( $page ) {
642 $match = isset( $this->namespaces[$page->page_namespace] );
643 return $this->invert xor $match;
644 }
645 }
646
647
648 /**
649 * Dump output filter to include only the last revision in each page sequence.
650 */
651 class DumpLatestFilter extends DumpFilter {
652 var $page, $pageString, $rev, $revString;
653
654 function writeOpenPage( $page, $string ) {
655 $this->page = $page;
656 $this->pageString = $string;
657 }
658
659 function writeClosePage( $string ) {
660 if( $this->rev ) {
661 $this->sink->writeOpenPage( $this->page, $this->pageString );
662 $this->sink->writeRevision( $this->rev, $this->revString );
663 $this->sink->writeClosePage( $string );
664 }
665 $this->rev = null;
666 $this->revString = null;
667 $this->page = null;
668 $this->pageString = null;
669 }
670
671 function writeRevision( $rev, $string ) {
672 if( $rev->rev_id == $this->page->page_latest ) {
673 $this->rev = $rev;
674 $this->revString = $string;
675 }
676 }
677 }
678
679 /**
680 * Base class for output stream; prints to stdout or buffer or whereever.
681 */
682 class DumpMultiWriter {
683 function DumpMultiWriter( $sinks ) {
684 $this->sinks = $sinks;
685 $this->count = count( $sinks );
686 }
687
688 function writeOpenStream( $string ) {
689 for( $i = 0; $i < $this->count; $i++ ) {
690 $this->sinks[$i]->writeOpenStream( $string );
691 }
692 }
693
694 function writeCloseStream( $string ) {
695 for( $i = 0; $i < $this->count; $i++ ) {
696 $this->sinks[$i]->writeCloseStream( $string );
697 }
698 }
699
700 function writeOpenPage( $page, $string ) {
701 for( $i = 0; $i < $this->count; $i++ ) {
702 $this->sinks[$i]->writeOpenPage( $page, $string );
703 }
704 }
705
706 function writeClosePage( $string ) {
707 for( $i = 0; $i < $this->count; $i++ ) {
708 $this->sinks[$i]->writeClosePage( $string );
709 }
710 }
711
712 function writeRevision( $rev, $string ) {
713 for( $i = 0; $i < $this->count; $i++ ) {
714 $this->sinks[$i]->writeRevision( $rev, $string );
715 }
716 }
717 }
718
719 function xmlsafe( $string ) {
720 $fname = 'xmlsafe';
721 wfProfileIn( $fname );
722
723 /**
724 * The page may contain old data which has not been properly normalized.
725 * Invalid UTF-8 sequences or forbidden control characters will make our
726 * XML output invalid, so be sure to strip them out.
727 */
728 $string = UtfNormal::cleanUp( $string );
729
730 $string = htmlspecialchars( $string );
731 wfProfileOut( $fname );
732 return $string;
733 }
734
735 ?>